package com.mljr.example.dao;


import com.ctakit.sdk.SdkApplication;
import com.ctakit.sdk.util.JsonUtils;
import com.mljr.example.bean.PageContent;

import java.util.List;

/**
 * Helper to the database, manages versions and creation
 */
public class PageContentDAO extends BaseDAO<PageContent> {

    public PageContentDAO() {
        super(SdkApplication.app());
    }


    @SuppressWarnings("unchecked")
    public <T> T getPageContent(String key, Class<T> clazz) {
        PageContent pageContent = this.getById(key);

        if (clazz.isAssignableFrom(PageContent.class)) {
            return (T) pageContent;
        }
        if (pageContent != null) {
            return JsonUtils.fromJson(pageContent.getValue(), clazz);
        }
        return null;
    }

    public <T> List<T> getPageListContent(String key, Class<T> clazz) {
        PageContent pageContent = this.getById(key);
        if (pageContent != null) {
            return JsonUtils.fromJsonToList(pageContent.getValue(), clazz);
        }
        return null;
    }

    public void setPageContent(String key, String value) {
        PageContent pageContent = new PageContent();
        pageContent.setKey(key);
        pageContent.setValue(value);
        this.save(pageContent);
    }

    @Override
    Class<PageContent> getClazz() {
        // TODO Auto-generated method stub
        return PageContent.class;
    }

}
